/*
 * Copyright (C) 2018 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xdlink.component.protocol.impl;

import com.xuexiang.xdlink.component.message.IDataInfo;
import com.xuexiang.xdlink.component.message.IRequestMessage;
import com.xuexiang.xdlink.component.message.IResponseMessage;
import com.xuexiang.xdlink.component.protocol.IProtocol;
import com.xuexiang.xdlink.component.protocol.OnProtocolListener;
import com.xuexiang.xdlink.exception.ProtocolException;

/**
 * 抽象协议
 *
 * @author xuexiang
 * @since 2018/8/13 下午10:52
 */
public abstract class AbstractProtocol implements IProtocol {

    /**
     * 协议监听器
     */
    private OnProtocolListener mOnProtocolListener;

    @Override
    public void setOnProtocolListener(OnProtocolListener listener) {
        mOnProtocolListener = listener;
    }

    @Override
    public void onReceivedMessage(IResponseMessage responseMessage) throws ProtocolException {
        if (mOnProtocolListener != null) {
            mOnProtocolListener.onReceivedMessage(responseMessage);
        } else {
            throw new ProtocolException("mOnProtocolListener is null, setOnProtocolListener() must be called!");
        }
    }

    @Override
    public void onReceivedDataInfo(IDataInfo dataInfo) throws ProtocolException {
        if (mOnProtocolListener != null) {
            mOnProtocolListener.onReceivedDataInfo(dataInfo);
        } else {
            throw new ProtocolException("mOnProtocolListener is null, setOnProtocolListener() must be called!");
        }
    }

    /**
     * 向设备回复消息
     *
     * @param requestMessage 请求协议消息体
     */
    @Override
    public void onReplyMessage(IRequestMessage requestMessage) throws ProtocolException {
        if (mOnProtocolListener != null) {
            mOnProtocolListener.onReplyData(requestMessage.toBytes());
        } else {
            throw new ProtocolException("mOnProtocolListener is null, setOnProtocolListener() must be called!");
        }
    }

    @Override
    public void recycle() {
        mOnProtocolListener = null;
    }
}
